package com.kapuscinski.saferoute.database;

import com.google.android.gms.maps.model.LatLngBounds;
import com.kapuscinski.saferoute.database.DatabaseContract.RoughnessEntry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String TAG = "DatabaseHelper";
	private static final String DATABASE_NAME = "RoughnessMonitor.db";
	private static final int DATABASE_VERSION = 1;

	private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
			+ RoughnessEntry.TABLE_NAME + " (" + RoughnessEntry._ID
			+ " INTEGER PRIMARY KEY," + RoughnessEntry.LATITUDE + " REAL, "
			+ RoughnessEntry.LONGITUDE + " REAL, "
			+ RoughnessEntry.ACCELERATION + " REAL, "
			+ RoughnessEntry.ACCURACY + " REAL " + ")";

	private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS "
			+ RoughnessEntry.TABLE_NAME;

	private SQLiteDatabase database;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_ENTRIES);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL(SQL_DELETE_ENTRIES);
		onCreate(db);
	}

	public int deleteAllData() {
		//1 as argument to fetch number of rows deleted
		return database.delete(RoughnessEntry.TABLE_NAME, "1", null);
	}

	public void openDatabaseInWriteMode() {
		database = this.getWritableDatabase();
	}

	public void addEntry(DataModel model) {
		ContentValues values = new ContentValues();
		values.put(RoughnessEntry.LATITUDE, model.getLatitude());
		values.put(RoughnessEntry.LONGITUDE, model.getLongitude());
		values.put(RoughnessEntry.ACCELERATION, model.getAcceleration());
		values.put(RoughnessEntry.ACCURACY, model.getAccuracy());
		database.insert(RoughnessEntry.TABLE_NAME, null, values);
	}

	//returns data that can be presented with current map bounds
	public Cursor getCursorForBounds(LatLngBounds mapBounds) {
		String selection = DatabaseContract.RoughnessEntry.LATITUDE + " >= "
				+ String.valueOf(mapBounds.southwest.latitude) + " AND "
				+ DatabaseContract.RoughnessEntry.LATITUDE + " <= "
				+ String.valueOf(mapBounds.northeast.latitude) + " AND "
				+ RoughnessEntry.LONGITUDE + " >= "
				+ String.valueOf(mapBounds.southwest.longitude) + " AND "
				+ RoughnessEntry.LONGITUDE + " <= "
				+ String.valueOf(mapBounds.northeast.longitude);
		return database.query(RoughnessEntry.TABLE_NAME, null, selection, null, null,
				null, null);
	}

	public Cursor getCursor() {
		return database.query(RoughnessEntry.TABLE_NAME, null, null, null,
				null, null, null);
	}

}
